package com.mic.yzzn.plc.common.instructions.basic;

import org.apache.commons.lang.StringUtils;

/**
 * Created by ASH on 16/3/7.
 */
public class PLCResponseInstruction extends PLCInstruction
{
    public static final String
            PLCInstructionTypeResponseCode = "$",
            PLCInstructionTypeErrorResponseCode = "!";

    public static final String
            READ_RESPONSE_CODE = "RC",
            WRITE_RESPONSE_CODE = "WC";
            
    /** 响应代码 */
    protected String responseCode;

    public void setResponseCode(String responseCode)
    {
        this.responseCode = responseCode;
    }

    /**
     * 计算并返回自己每一位的异或
     */
    @Override
    protected int getXORByBit()
    {
        int i = 0;
        int result = 0;
        for (i = 0; i < responseCode.length(); ++i)
        {
            result ^= responseCode.charAt(i);
        }

        return super.getXORByBit() ^ result;
    }

    /**
     * 转换为字符串
     */
    @Override
    public String toString()
    {
        // 拼接指令字符串
        StringBuffer buffer = new StringBuffer();
        buffer.append(instructionHeader);
        buffer.append(locationNumber_high);
        buffer.append(locationNumber_low);
        buffer.append(instructionTypeCode);
        buffer.append(responseCode);
        buffer.append(getBBC_high());
        buffer.append(getBBC_low());
        buffer.append(instructionEnd);

        return buffer.toString();
    }
    
    /**
     * 用字符串初始化
     */
    @Override
    public String initWithString(String instructionString) throws IllegalArgumentException
    {
    	String tempResult = super.initWithString(instructionString);
    	
//    	System.out.println(tempResult);
    	
    	String typeCode = tempResult.substring(0, 1);
    	
    	// 检测响应类型码是否正常
    	if (!typeCode.equals(PLCResponseInstruction.PLCInstructionTypeErrorResponseCode) 
    			&& !typeCode.equals(PLCResponseInstruction.PLCInstructionTypeResponseCode))
		{
			throw new IllegalAccessError("response type code must be \"$\" or \"!\"");
		}
    	
    	// 设置响应类型码
    	instructionTypeCode = typeCode;
    	
    	// 截取响应类型码
    	tempResult = StringUtils.substringAfter(tempResult, typeCode);
    	
    	// 如果是错误响应则设置错误代码
    	if (typeCode.equals(PLCResponseInstruction.PLCInstructionTypeErrorResponseCode))
		{
    		responseCode = tempResult;
    		tempResult = StringUtils.substringAfter(tempResult, responseCode);
		}
    	
    	return tempResult;
    }
}
